import PerfectScrollbar from 'perfect-scrollbar';
import 'perfect-scrollbar/css/perfect-scrollbar.css';

export default {
  mounted(el) {
    el._ps = new PerfectScrollbar(el, {
      suppressScrollX: true,
      wheelPropagation: false,
      wheelSpeed: 0.5,
    });
    el.scrollToTop = (smooth = true) => {
      if (smooth) {
        const duration = 500;
        const start = el.scrollTop;
        const startTime = performance.now();
        const animate = (currentTime) => {
          const elapsed = currentTime - startTime;
          const progress = Math.min(elapsed / duration, 1);
          el.scrollTop = start * (1 - progress);
          if (progress < 1) {
            requestAnimationFrame(animate);
          } else {
            el._ps.update();
          }
        };
        requestAnimationFrame(animate);
      } else {
        el.scrollTop = 0;
        el._ps.update();
      }
    };
  },
  updated(el) {
    el._ps.update();
  },
  unmounted(el) {
    if (el._ps) {
      el._ps.destroy();
      delete el._ps;
    }
  }
}